package com.zr0726.news.web;

import com.zr0726.news.po.User;
import com.zr0726.news.service.NewsService;
import com.zr0726.news.service.TagService;
import com.zr0726.news.service.TypeService;
import com.zr0726.news.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.query.Param;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


@Controller
public class IndexController {

    @Autowired
    private NewsService newsService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @GetMapping("/")
    public String index(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC)
                        Pageable pageable, Model model){
        model.addAttribute("page", newsService.listNews(pageable));
        model.addAttribute("types", typeService.listTypeTop(5));
        model.addAttribute("tags", tagService.listTagTop(5));
        model.addAttribute("recommendNews", newsService.listRecommendNewsTop(3));
        return "index";
    }

    @PostMapping("/search")
    public String search(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC)
                         Pageable pageable, @RequestParam String query, Model model){
        model.addAttribute("page", newsService.listNews("%"+query+"%", pageable));
        model.addAttribute("query", query);
        return "search";
    }

    @RequestMapping("/news/{id}")
    public String news(@PathVariable Long id, Model model){
        model.addAttribute("news", newsService.getAndConvertNews(id));
        return "new";
    }

}
